package com.itheima.mm.controller;

import com.itheima.mm.constant.JwtClaimsConstant;
import com.itheima.mm.dto.UserLoginDTO;
import com.itheima.mm.entity.Result;
import com.itheima.mm.pojo.User;
import com.itheima.mm.properties.JwtProperties;
import com.itheima.mm.service.UserService;
import com.itheima.mm.utils.JwtUtil;
import com.itheima.mm.vo.UserLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description UserController
 * @Author songyu
 * @Date 2023-09-19
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户登录页面")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 登入
     *
     * @return
     * @param: userLoginDTO
     **/
    @PostMapping("/login.do")
    @ApiOperation("登入")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO) {
        log.info("用户登录：{}", userLoginDTO);
        User user = userService.login(userLoginDTO);

        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());

        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);

        UserLoginVO build = UserLoginVO.builder()
                .id(user.getId())
                .token(token)
                .build();

        return Result.success(build);
    }

    /**
     * 退出
     *
     * @return
     **/
    @ApiOperation("退出")
    @PostMapping("/logout.do")
    public Result<String> logout() {
        return Result.success();
    }


}
